import { Menu } from 'antd'
import styles from './index.module.less'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import { useStore } from '../../store'
import type { MenuProps } from 'antd'
import React, { useEffect, useState } from 'react'
import { Menu as IMenu } from '../../types/api'
import * as Icons from '@ant-design/icons'

const SideMenu = () => {
  const { pathname } = useLocation()
  //获取loader数据
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const loaderData: any = useRouteLoaderData('layout')
  const state = useStore()
  const navigate = useNavigate()
  const [menuList, setMenuList] = useState<MenuItem[]>([])
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  type MenuItem = Required<MenuProps>['items'][number]
  function getItem(
    label: React.ReactNode,
    key?: React.Key | null,
    icon?: React.ReactNode,
    children?: MenuItem[]
  ): MenuItem {
    return {
      label,
      key,
      icon,
      children
    } as MenuItem
  }
  function createIcon(name?: string) {
    if (!name) return <></>
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const customerIcons: { [key: string]: any } = Icons
    const icon = customerIcons[name]
    if (!icon) return <></>
    return React.createElement(icon)
  }
  //递归生成菜单
  const getTreeMenu = (menuList: IMenu.MenuItem[], treeList: MenuItem[] = []) => {
    menuList.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (item.children && !item.buttons)
          return treeList.push(
            getItem(item.menuName, item.path || index, createIcon(item.icon), getTreeMenu(item.children || []))
          )
        treeList.push(getItem(item.menuName, item.path || index, createIcon(item.icon)))
      }
    })
    return treeList
  }
  useEffect(() => {
    const treeMenuList = getTreeMenu(loaderData.menuList)
    setMenuList(treeMenuList)
    setSelectedKeys([pathname])
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname])
  const handleClickLogo = () => {
    navigate('/welcome')
  }
  const handleClickMenu = ({ key }: { key: string }) => {
    console.log('key', key)

    setSelectedKeys([key])
    navigate(key)
  }
  return (
    <div>
      <div className={styles.logo} onClick={handleClickLogo}>
        <img src='/img/logo.png' className={styles.img} />
        <span>{state.collapsed ? '' : '慕慕货运'}</span>
      </div>
      <Menu selectedKeys={selectedKeys} mode='inline' theme='dark' items={menuList} onClick={handleClickMenu} />
    </div>
  )
}
export default SideMenu
